import javax.swing.*;
import java.awt.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import java.util.Properties;
import java.util.*;
import java.awt.event .*;


import org.apache.ddlutils.io.DatabaseIO;
import org.apache.ddlutils.model.Database;
import javax.sql.DataSource;
import org.apache.commons.beanutils.DynaBean;
import org.apache.ddlutils.Platform;
import org.apache.ddlutils.PlatformFactory;
import org.apache.ddlutils.model.Database;

public class MySimpleApp
{
    /* the default framework is embedded*/
    public String framework = "embedded";
    public String driver = "org.apache.derby.jdbc.EmbeddedDriver";
    public String protocol = "jdbc:derby:";
	Connection conn = null;
	JTextField userNameTF = null;
	JTextField passwordTF = null;
	JFrame frame = new JFrame("HelloWorldSwing");

	String userName = null;
    public static void main(String[] args)
    {
        //new MySimpleApp().go(args);
        if(args.length ==0)
		{
				System.out.println("Usage java MySimpleApp <schema_file_location>" );
				System.exit(1);
		}
        try
        {
			MySimpleApp msa = new MySimpleApp();

			String fileName=args[0];
			Database db = msa.readDatabaseFromXML(fileName);
				System.out.println("Completed reading schema from XML file");
			msa.createDatabase(db);
				System.out.println("Created basic database.");
			msa.establishDBConnection();
				System.out.println("Connected to database derbyDB");
			msa.createTables(db);
				System.out.println("Created all tables schema.");
			msa.insertData(db);
				System.out.println("Inserted data without SQL.");
			msa.doInsertsWithSQL();
				System.out.println("Inserted data with SQL.");
			msa.buildUI();
			//msa.launchNextScreen();
		}catch(Exception e)
		{
			e.printStackTrace();
		}
    }
	public Database readDatabaseFromXML(String fileName) throws Exception
	{
		    return new DatabaseIO().read(fileName);
	}
	void createDatabase(Database   database) throws Exception
	{
		Platform platform = PlatformFactory.createNewPlatformInstance("derby");
		System.out.println("Created platform..");
		Properties props = new Properties();
		props.put("user", "scott");
		props.put("password", "tiger");
		platform.createDatabase(driver,protocol +"derbyDB;create=true","scott","tiger",props);
		System.out.println("Created database...");
	}
	void createTables(Database   database) throws Exception
	{
			Platform platform = PlatformFactory.createNewPlatformInstance("derby");
			platform.createTables(conn, database, true, true);
			conn.setAutoCommit(true);
	}
    void establishDBConnection() throws Exception
    {
		Class.forName(driver).newInstance();
		Properties props = new Properties();
		props.put("user", "scott");
		props.put("password", "tiger");
		conn = DriverManager.getConnection(protocol +
				"derbyDB;create=true", props);
		conn.setAutoCommit(true);
	}
	public void insertData(Database   database) throws Exception
	{
		    Platform platform = PlatformFactory.createNewPlatformInstance("derby");

		    DynaBean userData = database.createDynaBeanFor("userData", false);
		    userData.set("userName",     "tiger");
		    userData.set("password",     "singh");
		    platform.insert(conn, database, userData);
			System.out.println("Inserted Tiger data into userData table..");
		    userData = database.createDynaBeanFor("userData", false);
			userData.set("userName",     "vijay");
		    userData.set("password",     "woods");
		    platform.insert(conn, database, userData);
		    System.out.println("Inserted Vijay data into userData table..");
		    System.out.println("XXXXXXXXXXXXXXXX Done inserting userData XXXXXXXXXXXXXXX");

		    DynaBean coursesData = database.createDynaBeanFor("CoursesPlayed", false);
		    coursesData.set("userName",     "tiger");
			coursesData.set("courseName",     "Pinehurst GC");
		    platform.insert(conn, database, coursesData);

		    coursesData = database.createDynaBeanFor("CoursesPlayed", false);
			coursesData.set("userName",     "tiger");
			coursesData.set("courseName",     "Lionspaw GC");
		    platform.insert(conn, database, coursesData);

		    coursesData = database.createDynaBeanFor("CoursesPlayed", false);
			coursesData.set("userName",     "tiger");
			coursesData.set("courseName",     "Westminster GC");
		    platform.insert(conn, database, coursesData);

		    System.out.println("XXXXXXXXXXXXXXXX Done inserting userData XXXXXXXXXXXXXXX");

	}
    void doInsertsWithSQL() throws Exception
    {

		try
		{
			Statement s = conn.createStatement();
			s.execute("insert into CoursesPlayed values ('vijay','Pinehurst GC')");
			s.execute("insert into CoursesPlayed values ('vijay','Lionspaw GC')");
			s.execute("insert into CoursesPlayed values ('vijay','Westminster GC')");
			s.execute("insert into CoursesPlayed values ('vijay','Kapaluo GC')");

			System.out.println("XXXXXXXXXXXXXXXX Done inserting vijay data XXXXXXXXXXXXXXX");
			s.close();
		}catch(Exception e)
		{
			System.out.println("Database already created.");
		}
	}
	void launchNextScreen()
	{


		JPanel panel = new JPanel();
		GridBagLayout gridbag = new GridBagLayout();
		panel.setLayout(gridbag);
		GridBagConstraints constraints = new GridBagConstraints();
		constraints.gridx = 0;
		constraints.gridy = 0;
		constraints.gridwidth = 1;
		constraints.gridheight = 1;
		constraints.insets = new Insets(10,10,10,10);
		constraints.anchor = GridBagConstraints.CENTER;
		JLabel  lbl1 = new JLabel("List Of Golf Courses");
		panel.add(lbl1);
		gridbag.setConstraints(lbl1, constraints);

		constraints.gridx = 2;
		constraints.gridy = 0;
		constraints.gridwidth = 1;
		constraints.gridheight = 1;
		constraints.anchor = GridBagConstraints.CENTER;
		JLabel  lbl2 = new JLabel("Golf Courses I played");
		panel.add(lbl2);
		gridbag.setConstraints(lbl2, constraints);


		constraints.gridx = 0;
		constraints.gridy = 1;
		constraints.gridwidth = 1;
		constraints.gridheight = 1;
		constraints.anchor = GridBagConstraints.NORTH;
		String[] data = {"Augusta National", "Pinehurst GC", "Lionspaw GC", "Westminster GC","Kapaluo GC"};
		JList  allList = new JList(data);
		panel.add(allList);
		gridbag.setConstraints(allList, constraints);
		//
		constraints.gridx = 2;
		constraints.gridy = 1;
		constraints.gridwidth = 1;
		constraints.gridheight = 1;
		constraints.anchor = GridBagConstraints.NORTH;
		String[] mydata = null;
		try{
	    	mydata = getMyList(userName);
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		JList  myList = new JList(mydata);
		panel.add(myList);
		gridbag.setConstraints(myList, constraints);
		//frame.removeAll();
		frame.setContentPane(panel);
		//panel.setOpaque(true);
		//frame.pack();
		frame.validate();


		frame.setSize(400,300);

		frame.setVisible(true);
	}
	String[] getMyList(String userName) throws Exception
	{
		Vector  myCourses = new Vector();
		Statement s = conn.createStatement();
		ResultSet rs = s.executeQuery("SELECT courseName FROM CoursesPlayed WHERE userName='"+userName+"'");
		while(rs.next())
		{
			String str =rs.getString(1);
			if(str != null)
				myCourses.addElement(str);
		}
		String myList[] = new String[myCourses.size()];
		for(int i =0; i < myCourses.size(); i++)
			myList[i] = (String)myCourses.elementAt(i);
		return myList;
	}
	boolean validateUser(String userName, String password) throws Exception
	{
		Statement s = conn.createStatement();
		ResultSet rs = s.executeQuery("SELECT COUNT(*) FROM userData WHERE userName='"+userName+"' and password='"+password+"'");
		int count = -1;
		while(rs.next())
		{
			count = rs.getInt(1);
		}
		return count==1 ? true : false;


	}
    void buildUI()
    {
		JFrame.setDefaultLookAndFeelDecorated(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		JPanel panel = new JPanel();
		GridBagLayout gridbag = new GridBagLayout();
		panel.setLayout(gridbag);

		////////////////////////////////
		GridBagConstraints constraints = new GridBagConstraints();
		constraints.gridx = 0;
		constraints.gridy = 0;
		constraints.gridwidth = 3;
		constraints.gridheight = 1;
		constraints.insets = new Insets(10,10,10,10);
		constraints.anchor = GridBagConstraints.EAST;
		JLabel  lbl1 = new JLabel("User Name");
		panel.add(lbl1);
		gridbag.setConstraints(lbl1, constraints);

		///////////////////////////
		constraints.gridx = 4;
		constraints.gridy = 0;
		constraints.gridwidth = 3;
		constraints.anchor = GridBagConstraints.WEST;


		userNameTF = new JTextField(20);
		panel.add(userNameTF);
		gridbag.setConstraints(userNameTF, constraints);

		/////////////////////////////
		constraints.gridx = 0;
		constraints.gridy = 1;
		constraints.gridwidth = 3;
		constraints.anchor = GridBagConstraints.EAST;
		JLabel  lbl2 = new JLabel("Password");
		panel.add(lbl2);
		gridbag.setConstraints(lbl2, constraints);

		/////////////////////////////////
		constraints.gridx = 4;
		constraints.gridy = 1;
		constraints.gridwidth = 3;
		constraints.anchor = GridBagConstraints.WEST;


		passwordTF = new JPasswordField(20);
		gridbag.setConstraints(passwordTF, constraints);
		panel.add(passwordTF);


		//////////////////////////////////////
		JPanel p = new JPanel();
		JButton  okBtn = new JButton("Login");
		okBtn.addActionListener(new ActionListener()
						{
						public void actionPerformed(ActionEvent e)
						{
							System.out.println("userNameTF text :"+userNameTF.getText());
							System.out.println("passwordTF text :"+passwordTF.getText());
							try
							{
								if(validateUser(userNameTF.getText(),passwordTF.getText() ))
								{
									userName = userNameTF.getText();
									launchNextScreen();
								}
								else
								{
									userNameTF.setText("");
									passwordTF.setText("");
								}

							}catch(Exception ex)
							{
									ex.printStackTrace();
							}
						}
					}
			);



		p.add(okBtn);
		JButton  cancelBtn = new JButton("Cancel");
		p.add(cancelBtn);

		constraints.gridx = 1;
		constraints.gridy = 2;
		constraints.gridwidth = 6;
		constraints.anchor = GridBagConstraints.CENTER;

		gridbag.setConstraints(p, constraints);
		panel.setOpaque(true);
		panel.add(p);

		frame.getContentPane().add(panel);
		frame.pack();
		frame.setSize(400,300);

		frame.setVisible(true);

	}

}
